import 'dart:async';

import 'package:chewie/chewie.dart';
import 'package:flutter/services.dart';
import 'package:safetymonitor/app/components/video/video_controls_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:video_player/video_player.dart';

///基于CheWie二次封装
///demo:
///VideoPlayWidget(
///                  url: XXX,
///                  autoPlay: true,
///                  isDispose: true,
///                  ...
///                )
class VideoPlayWidget extends StatefulWidget {
  const VideoPlayWidget({
    super.key,
    // 视频播放链接
    this.url,
    // 自动播放
    this.autoPlay = false,
    // 循环播放
    this.looping = false,
    // 视频的纵横比--宽/高
    this.aspectRatio = 16 / 9,
    // 是否允许全屏
    this.allowFullScreen = true,
    // 是否允许视频速度的改变
    this.allowPlaybackSpeedChanging = true,

    /// 退出全屏回调
    this.onExitFullscreen,

    /// 是否是直播
    this.isLive = false,
  });

  final String? url;
  final bool autoPlay;
  final bool looping;
  final bool allowFullScreen;
  final bool allowPlaybackSpeedChanging;
  final double aspectRatio;
  final void Function()? onExitFullscreen;
  final bool isLive;

  @override
  VideoPlayWidgetState createState() => VideoPlayWidgetState();
}
class VideoPlayWidgetState extends State<VideoPlayWidget> {
  VideoPlayerController? _videoPlayerController;
  ChewieController? _cheWieController;
  RxBool isShowBack = false.obs;

  @override
  void initState() {
    super.initState();
    init(widget.url!);
  }

  init(String url) async {
    // widget.url：播放地址
    _videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(url));
    await _videoPlayerController?.initialize();
    _cheWieController = ChewieController(
      //这样将使用软件解码而不是硬件解码。在某些设备上，软件解码可能更加可靠。
      autoInitialize: true,
      // 尝试设置为 true
      videoPlayerController: _videoPlayerController!,
      // 自动播放
      autoPlay: widget.autoPlay,
      // 循环播放
      looping: widget.looping,
      // 视频的纵横比--宽/高
      aspectRatio: widget.aspectRatio,
      // 是否允许视频速度的改变
      allowPlaybackSpeedChanging: widget.allowPlaybackSpeedChanging,
      // 是否允许全屏
      allowFullScreen: widget.allowFullScreen,
      // 定义自定义控件
      customControls: Obx(() => VideoControlsWidget(
            overlayUI: isShowBack.value ? _videoPlayTopBar() : null,
            bottomGradient: _blackLinearGradient(),
            isLive: widget.isLive,
          )),
    )..addListener(() {
        if (!_cheWieController!.isFullScreen) {
          isShowBack.value = false;
          // 在这里处理退出全屏的逻辑
          // ...
          ///在 Chewie 退出全屏的回调中调用 SystemChrome.setPreferredOrientations 强制竖屏可能没有效果的原因是，Chewie 在退出全屏时会还原之前的系统方向设置，
          ///导致你在 Chewie 退出全屏时设置的方向又被还原了。解决这个问题的一个方法是，在 Chewie 退出全屏的回调中，延迟一段时间再设置方向。你可以使用 Timer 来实现延迟，
          ///代码示例如下：
          setPortraitDelayed();
          widget.onExitFullscreen?.call();
        } else {
          isShowBack.value = true;
        }
      });
    setState(() {});
  }

  static void setPortraitDelayed() {
    Timer(const Duration(milliseconds: 600), () {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
    });
  }

  @override
  Widget build(BuildContext context) {
    final double width = MediaQuery.of(context).size.width;
    final double height = width / widget.aspectRatio;
    return SizedBox(
      width: width,
      height: height,
      child: _videoPlayerController!.value.isInitialized
          ? Chewie(
              controller: _cheWieController!,
            )
          : const Center(
              child: CircularProgressIndicator(),
            ),
    );
  }

  @override
  void dispose() {
    _videoPlayerController?.dispose();
    _cheWieController?.dispose();
    super.dispose();
  }

  void play() {
    _cheWieController!.play();
  }

  void pause() {
    _videoPlayerController!.pause();
  }

  //指定销毁_videoPlayerController控制器 释放资源
  void disVideoPlayerController() {
    _videoPlayerController?.dispose();
    //_cheWieController不能销毁 替换URL时会出问题！！！
    // _cheWieController?.dispose();
  }

  //设置之前的播放进度！
  void seekToWhenReady(int seconds) {
    bool hasSeeked = false; // 用于标记是否已经执行过 seek 操作
    _videoPlayerController?.addListener(() {
      if (!_videoPlayerController!.value.isInitialized) {
        return;
      }

      if (!_videoPlayerController!.value.isBuffering) {
        // 视频加载完成
        if (!hasSeeked) {
          // 执行 seek 操作
          _videoPlayerController?.seekTo(Duration(seconds: seconds));
          hasSeeked = true;
        }
      }
    });
  }

  //获取总时长：
  Duration? totalDuration() {
    return _cheWieController?.videoPlayerController.value.duration;
  }

  //获取当前播放进度：
  Duration? currentPositionDuration() {
    return _cheWieController?.videoPlayerController.value.position;
  }

  void enterFullscreen() {
    _cheWieController?.enterFullScreen();
  }

  /// 播放视频的 TopBar
  Widget _videoPlayTopBar() {
    return Container(
      padding: const EdgeInsets.only(right: 8),
      // 渐变背景色
      decoration: BoxDecoration(gradient: _blackLinearGradient(fromTop: true)),
      child: const Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          BackButton(color: Colors.white),
          // Icon(Icons.more_vert_rounded, color: Colors.white, size: 20),
        ],
      ),
    );
  }

  /// 渐变背景色
  LinearGradient _blackLinearGradient({bool fromTop = false}) {
    return LinearGradient(
      begin: fromTop ? Alignment.topCenter : Alignment.bottomCenter,
      end: fromTop ? Alignment.bottomCenter : Alignment.topCenter,
      colors: const [
        Colors.black54,
        Colors.black45,
        Colors.black38,
        Colors.black26,
        Colors.black12,
        Colors.transparent
        // Colors.red,
        // Colors.blue,
        // Colors.grey,
        // Colors.green,
      ],
    );
  }
}
